import time

from django.utils.deprecation import MiddlewareMixin

# 统计每个请求的请求耗时
class MyMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """
        客户端发来请求与路由匹配执行之前执行
        返回值是None时，继续向后执行下一个中间件的process_request或路由映射
        返回值是HttpResponse对象时，不执行路由与views函数，直接执行该中间件与其之前的process_response，倒序执行
        :param request:
        :return:
        """
        request.start_time = time.time()

    def process_response(self, request, response):
        '''
        在response返回给客户端之前执行，也就值最后经过
        必须返回HttpResponse对象
        :param request:
        :param response:
        :return:
        '''
        if hasattr(request, 'start_time'):
            duration = time.time() - request.start_time
            print(f"{request.path}： 请求耗时{duration:.3f}秒。")
        return response
